import 'package:flutter/material.dart';
import 'package:flutter_shop/jpush/jpush_jumper.dart';
import 'package:flutter_shop/jpush/jpush_module_key.dart';
import 'package:flutter_shop/jpush/jpush_msg_data.dart';
import 'package:flutter_shop/utils/log_utils.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

///Title:极光推送消息接收 <br/>
///Description:注意:如果使用NavigatorUtils跳转,必须在index_page里绑定context <br/>
///author:xiemiao <br/>
///date: 2020-03-02 <br/>
///version 1.0 <br/>
class JpushReceiver {
  static const String TAG = "JpushReceiver";

  BuildContext context;

  ///添加消息监听,必须在jpush.setUp之前调用
  void addEventHandler(JPush jpush) {
    jpush.addEventHandler(
      // 接收通知回调方法。
      onReceiveNotification: (Map<String, dynamic> message) async {
        Log.d("onReceiveNotification: $message", tag: TAG);
      },
      // 点击通知回调方法。
      onOpenNotification: (Map<String, dynamic> message) async {
        Log.d("onOpenNotification: $message", tag: TAG);
        _processOpenNotification(message);
      },
      // 接收自定义消息回调方法。
      onReceiveMessage: (Map<String, dynamic> message) async {
        Log.d("onReceiveMessage: $message", tag: TAG);
      },
    );
  }

  ///绑定上下文
  ///The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
  ///所以暂时需要在index_page里去绑定context
  void bindContext(BuildContext context) {
    this.context = context;
  }

  ///处理点击通知
  void _processOpenNotification(Map<String, dynamic> message) async {
    ///获取扩展消息
    Map<dynamic, dynamic> extras = message['extras'];
    String json = extras['cn.jpush.android.EXTRA'];
    JpushMsgData entity = Utils.parseJson2Obj(json, (v) => JpushMsgData().fromJson(v));

    if (this.context != null) {
      JpushJumper.jump(context, JpushModuleKey.getRouterPath(entity.moduleKey), entity);
    }
  }
}
